//#define __DEBUG__
// by Xeno
#define THIS_FILE "fn_createinf.sqf"
#include "x_setup.sqf"

private ["_radius", "_pos", "_nr", "_nrg", "_typenr", "_i", "_newgroup", "_units", "_pos_center", "_do_patrol", "_ret_grps","_cnt_defend","_homed"];
__TRACE_1("","_this")
_pos_center = _this select 4;
_radius = _this select 5;
_do_patrol = if (_radius < 50) then {false} else {if (count _this == 7) then {_this select 6} else {false}};

_ret_grps = [];
_pos = [];
for "_nr" from 0 to 1 do {
	_nrg = _this select (1 + (_nr * 2));
	if (_nrg > 0) then {
		if (GVAR(MissionType) == 2) then {_nrg = _nrg + 2};
		_typenr = _this select (_nr * 2);
		// When set to defend, a third of the units will be in patrol
		_cnt_defend = floor(_nrg * 0.7);
		// When set to patrol, a third of the units are left as defenders
		if (_do_patrol) then { _cnt_defend = floor(_nrg * 0.333) };
		for "_i" from 1 to _nrg do {
			_newgroup = [GVAR(side_enemy)] call FUNC(creategroup);
			_unit_array = [_typenr, GVAR(enemy_side)] call FUNC(getunitliste);
			if (_radius > 0) then {
				_pos = [_pos_center, _radius] call FUNC(GetRanPointCircle);
				if (count _pos == 0) then {
					for "_ee" from 0 to 99 do {_pos = [_pos_center, _radius] call FUNC(GetRanPointCircle);if (count _pos > 0) exitWith {}};
				};
			} else {
				_pos = _pos_center;
			};
			_units = [_pos, _unit_array select 0, _newgroup] call FUNC(makemgroup);
			__TRACE_1("","_units")
			_newgroup allowFleeing 0;
			if (_cnt_defend > 0) then {
				_newgroup setCombatMode "YELLOW";
				_newgroup setFormation (["COLUMN","STAG COLUMN","WEDGE","ECH LEFT","ECH RIGHT","VEE","LINE","DIAMOND"] call FUNC(RandomArrayVal));
				_newgroup setFormDir (floor random 360);
				_newgroup setSpeedMode "NORMAL";
			};
			_ret_grps set [count _ret_grps, _newgroup];
			//TYRGHEN - When spawning large groupes of IAs, we have a chance to have some being in the non selected mode
			if (_cnt_defend <= 0) then {
				[_newgroup, _pos, [_pos_center, _radius], [5, 15, 30], "this call d_fnc_grmakesearch"] spawn FUNC(MakePatrolWPX);
			} else {
				_newgroup setVariable [QGVAR(defend), true];
				_homed = false;
				// We give a chance to spawn homed units as well
				if (random(10) > 6) then {
					_homed = [_newgroup, _pos_center] call FUNC(taskHomed);
				};
				if !(_homed) then {
					[_newgroup, _pos_center] spawn FUNC(taskDefend);
				};
			};
			GVAR(x_sm_rem_ar) = [GVAR(x_sm_rem_ar), _units] call FUNC(arrayPushStack);
			if (GVAR(doRespawnGroups)) then {
				GVAR(reduce_groups) set [count GVAR(reduce_groups), _newgroup];
			};
			__DEC(_cnt_defend);
		};
	};
};
_ret_grps